<template>
  <div>
    <!-- 隐藏的输入字段 -->
    <input id="topicId" type="hidden" value=""/>
    <input id="isAdmin" type="hidden" value=""/>
    <input id="STATICURL" type="hidden" value="//static.clewm.net/cli"/>

    <!-- 加载动画 -->
    <div class="loadingWrap">
      <img alt="loading" src="../../assets/images/cbd0851f409c.gif"/>
    </div>

    <!-- 主要内容区域 -->
    <div class="scrollDom">
      <div class="page-community">
        <div class="community-wrap">
          <div class="community-wrapper clearfix" id="vue-app">
            <div class="avoid-category-fixed-scroll">
              <div class="search-and-select">
                <div class="fixed-logo-block">
                  <img alt="草料二维码生成器" class="fixed-cliicon-logo" height="27" src="../../assets/images/60edce821c50.png"/>
                  <div class="fixed-cli-text">草料社区</div>
                </div>
                <div class="comment-type-wrap" id="category-commonet-wrap">
                  <ul class="fir-category-ul comment-type-ul" id="fir-category-ul">
                    <div class="init-empty-category-wrap">
                      <div class="m-r-md empty-line" style="width: 100px;"></div>
                      <div class="m-r-md empty-line" style="width: 100px;"></div>
                      <div class="m-r-md empty-line" style="width: 100px;"></div>
                      <div class="m-r-md empty-line" style="width: 100px;"></div>
                      <div class="m-r-md empty-line" style="width: 100px;"></div>
                      <div class="m-r-md empty-line" style="width: 100px;"></div>
                      <div class="m-r-md empty-line" style="width: 100px;"></div>
                      <div class="m-r-md empty-line" style="width: 100px;"></div>
                      <div class="m-r-md empty-line" style="width: 100px;"></div>
                    </div>
                  </ul>
                </div>
              </div>
            </div>

            <div class="page-community-wrapper-layout">
              <div class="sticky-baseline"></div>
              <div class="page-community-wrapper" id="page-community-wrapper">
                <div class="white">
                  <div class="content-box">
                    <!-- 标签页导航 -->
                    <div class="tab-wrap">
                      <ul class="tab-ul clearfix">
                        <li class="tab-li active" data-tab="mixflow-wrap" id="mixflow-wrap-tab">
                          <a class="tab-li-a" href="community/tab/mixflow.html">最新</a>
                        </li>
                        <li class="tab-li" data-tab="commonet-wrap" id="commonet-wrap-tab">
                          <div class="tab-divided-line"></div>
                          <a class="tab-li-a" href="community/tab/question.html">讨论</a>
                        </li>
                        <li class="tab-li" data-tab="client-wrap" id="client-wrap-tab">
                          <div class="tab-divided-line"></div>
                          <a class="tab-li-a" href="community/tab/article.html">文章</a>
                        </li>
                      </ul>

                      <!-- 右侧额外功能区 -->
                      <div class="right-extra">
                        <div class="search-help-container">
                          <div class="search-help">
                            <input class="search-help-input" id="search-help-input" name="search-help-input" placeholder="输入搜索内容"/>
                            <span class="clifont anticon-nav_search" id="search-help-btn"></span>
                          </div>
                        </div>
                        <button class="ask-question-btn" data-service-issue="" id="create-post-entry" type="button">发帖</button>
                        <div id="vue-root"></div>
                      </div>
                    </div>

                    <!-- 内容区域 -->
                    <!-- 最新内容区域 -->
                    <div class="comment-wrap conetnt-slide-wrap active" id="mixflow-wrap">
                      <div class="comment-lists-box" id="comment-lists-box"></div>
                      <div class="loading-more none">正在加载...</div>
                    </div>

                    <!-- 讨论内容区域 -->
                    <div class="comment-wrap conetnt-slide-wrap" id="commonet-wrap">
                      <div class="comment-lists-box" id="question-lists-box"></div>
                      <div class="loading-more none">正在加载...</div>
                    </div>

                    <div class="teach-help-wrap conetnt-slide-wrap" id="client-wrap">
                      <div class="teach-lists-box">
                        <ul class="client-ul" id="client-lists-ul"></ul>
                      </div>
                    </div>

                    <div class="product-update conetnt-slide-wrap" id="product-update">
                      <ul class="update-ul" id="product-update-ul"></ul>
                    </div>
                  </div>

                  <!-- 反馈模态框 -->
                  <div class="modal fade" data-backdrop="true" id="feedback-modal-tips">
                    <div class="modal-dialog" style="width: 800px;margin-top: 150px">
                      <div class="modal-content text-center">
                        <button aria-label="Close" class="close feedback-modal-close" data-dismiss="modal" id="feedback-modal-tips-close" type="button">
                          <span aria-hidden="true">×</span>
                        </button>
                        <h4><i class="fa fa-check-circle"></i>问题提交成功</h4>
                        <p class="sub-title first"><span class="bold">微信扫码关注"草料二维码"公众号，第一时间收到回复通知</span></p>
                        <p class="sub-title sec">也可以在「提问题」-「提问记录」中查看所有问题回复</p>
                        <button class="btn green btn-fw finish" data-dismiss="modal" type="button">完成</button>
                      </div>
                    </div>
                  </div>

                  <!-- 警告模态框 -->
                  <div class="modal fade" data-backdrop="true" id="modal-alert">
                    <div class="modal-dialog">
                      <div class="modal-content">
                        <div class="modal-header">
                          <button class="close" data-dismiss="modal" type="button">
                            <span aria-hidden="true">×</span>
                            <span class="sr-only">Close</span>
                          </button>
                          <h4 class="modal-title"></h4>
                        </div>
                        <div class="modal-body p-a-lg"></div>
                      </div>
                    </div>
                  </div>

                  <!-- 添加标签模态框 -->
                  <div class="modal fade" data-backdrop="true" id="comment-add-tag-modal">
                    <div class="modal-dialog" style="width: 800px;margin-top: 150px">
                      <div class="modal-content">
                        <div class="modal-header">
                          <button class="close" data-dismiss="modal" type="button">
                            <span aria-hidden="true">×</span>
                            <span class="sr-only">关闭</span>
                          </button>
                          <h4 class="modal-title">添加标签</h4>
                        </div>
                        <div class="modal-body">
                          <div class="modal-tags-wrap" id="modal-tags-wrap"></div>
                        </div>
                        <div class="modal-footer">
                          <button class="btn btn-default" data-dismiss="modal" type="button">关闭</button>
                          <button class="btn btn-primary green" id="add-tag-button" type="button">确定</button>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 编辑来源模态框 -->
                  <div class="modal fade" data-backdrop="true" id="edit-source-modal">
                    <div class="modal-dialog" style="width: 800px;margin-top: 150px">
                      <div class="modal-content">
                        <div class="modal-header">
                          <button class="close" data-dismiss="modal" type="button">
                            <span aria-hidden="true">×</span>
                            <span class="sr-only">关闭</span>
                          </button>
                          <h4 class="modal-title">修改来源</h4>
                        </div>
                        <div class="modal-body">
                          <input autocomplete="off" class="edit-source-input" name="edit-source-input" type="text" value=""/>
                        </div>
                        <div class="modal-footer">
                          <button class="btn btn-default" data-dismiss="modal" type="button">关闭</button>
                          <button class="btn btn-primary green" id="edit-source-btn" type="button">确定</button>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 隐藏输入字段 -->
                  <input id="__pageType" type="hidden" value="page-community"/>
                  <input id="__tagId" type="hidden" value="[tag-id]"/>
                  <input id="__fromId" type="hidden" value="[from-id]"/>
                  <input id="__fromType" type="hidden" value="[from-type]"/>
                  <input id="__postType" type="hidden" value="[post-type]"/>
                  <input id="__scroll-top-anchor-id" type="hidden" value="[scroll-top-anchor-id]"/>

                  <!-- 小程序登录模态框 -->
                  <div class="miniprogram-login-modal">
                    <div class="login-modal">
                      <div class="login-modal-content">
                        <div class="title">你还未登录</div>
                        <div class="text">需要登录后才能提问和回复</div>
                      </div>
                      <div class="login-modal-button">
                        <button class="cancel-login">暂不登录</button>
                        <div class="button-divider"></div>
                        <button class="login">立即登录</button>
                      </div>
                    </div>
                  </div>

                  <div id="miniprogram-login-tip" style="display: none;">正在登录中...</div>
                </div>
              </div>

              <!-- 右侧信息块 -->
              <div id="right-side-info-block">
                <div class="category-wrap side-block">
                  <div class="category-info">
                    <h1 class="category-name side-block-name" title="-草料二维码用户社区">版块</h1>
                    <h2 class="category-description side-block-value"></h2>
                  </div>
                </div>
                <div class="side-block hot-category-block">
                  <div class="side-block-name">热门版块</div>
                  <div class="side-block-value" id="hot-category"></div>
                </div>
                <div class="side-block sub-category-block none">
                  <div class="side-block-name">子版块</div>
                  <div class="side-block-value" id="sub-category"></div>
                </div>
              </div>
            </div>
          </div>

          <input id="__tagsTitle" type="hidden" value=""/>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'

// === 合并的JS代码开始 ===

/**
 * 模拟数据服务
 * 为开发和测试提供假数据
 */
class MockDataService {
  constructor() {
    this.mockEnabled = true
  }

  getMockCommunityList(params = {}) {
    const { page = 1, pageSize = 20, categoryId = 0 } = params;

    return new Promise((resolve) => {
      setTimeout(() => {
        const mockItems = this.generateMockItems(pageSize, page);

        resolve({
          success: true,
          data: {
            list: mockItems,
            page: {
              current: page,
              total: 100,
              size: pageSize
            }
          }
        });
      }, 500);
    });
  }

  getMockCategories() {
    return new Promise((resolve) => {
      setTimeout(() => {
        const categories = [
          { id: 0, name: '全部', page_id: 0, count: null },
          { id: 1, name: '产品功能', page_id: 1, count: 7965 },
          { id: 2, name: '模板讨论', page_id: 2, count: 2160 },
          { id: 3, name: '标签制作', page_id: 3, count: 606 },
          { id: 4, name: '问题反馈', page_id: 4, count: 2231 },
          { id: 5, name: '行业交流', page_id: 5, count: 1538 },
          { id: 6, name: 'AI功能', page_id: 6, count: 59 }
        ];

        resolve({
          success: true,
          data: categories
        });
      }, 300);
    });
  }

  getMockCommunityCount(params = {}) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          success: true,
          data: {
            total: Math.floor(Math.random() * 100) + 50
          }
        });
      }, 200);
    });
  }

  generateMockItems(count, page) {
    const items = [];
    const types = ['comment', 'article'];

    const users = [
      '132****2222', '135****8888', '138****1234', '186****5678',
      '150****9999', '159****0000', '177****1111', '185****3333',
      'QR码专家', '二维码新手', '营销达人', '技术小白',
      'CLI用户001', 'CLI用户002', 'CLI用户003'
    ];

    const questionTitles = [
      '二维码扫描后显示"此二维码已失效或不存在"是什么原因？',
      '如何制作一个永久有效的二维码？',
      '批量生成二维码时，如何保证每个都是唯一的？',
      '二维码中间的logo图片可以自定义吗？',
      '扫描二维码后如何跳转到指定的微信小程序页面？',
      '二维码的容错率是什么意思？如何设置？',
      '为什么我的二维码在某些手机上扫不出来？',
      '如何统计二维码的扫描次数和用户来源？'
    ];

    const articleTitles = [
      '【教程】新手必看：5分钟学会制作专业二维码',
      '【分享】二维码在餐饮行业的10种创新应用',
      '【技巧】如何提高二维码的识别率和美观度',
      '【案例】某知名品牌的二维码营销成功案例分析'
    ];

    for (let i = 0; i < count; i++) {
      const id = (page - 1) * count + i + 1;
      const type = types[Math.floor(Math.random() * types.length)];
      const user = users[Math.floor(Math.random() * users.length)];

      let title;
      if (type === 'article') {
        title = articleTitles[Math.floor(Math.random() * articleTitles.length)];
      } else {
        title = questionTitles[Math.floor(Math.random() * questionTitles.length)];
      }

      const item = {
        id: id,
        target_type: type,
        title: title,
        content: this.generateMockContent(type),
        user_name: user,
        user_avatar: '/assets/mock-avatars/default-user.png',
        created_time: this.generateRandomDate(),
        view_count: Math.floor(Math.random() * 2000) + 10,
        reply_count: type === 'comment' ? Math.floor(Math.random() * 15) : Math.floor(Math.random() * 50),
        tags: this.generateMockTags(1),
        is_admin: Math.random() > 0.9,
        category_id: Math.floor(Math.random() * 6) + 1,
        source_link: Math.random() > 0.7 ? '/template/detail/mock-template' : '',
        source_name: Math.random() > 0.7 ? '模拟模板' : '',
        ...this.generateTypeSpecificData(type)
      };

      items.push(item);
    }

    return items;
  }

  generateMockContent(type = 'comment') {
    const questionContents = [
      '我在使用过程中遇到了这个问题，尝试了各种方法都没解决，求助各位大佬！',
      '这个功能对我的业务很重要，希望能得到详细的解答，谢谢！',
      '新手求助，刚开始使用二维码功能，不太了解具体操作流程。'
    ];

    const articleContents = [
      '根据我多年的实践经验，总结了一套完整的解决方案，希望对大家有帮助。详细步骤如下...',
      '在实际项目中，我们团队积累了一些宝贵的经验，现在分享给大家，避免踩坑。'
    ];

    if (type === 'article') {
      return articleContents[Math.floor(Math.random() * articleContents.length)];
    }

    return questionContents[Math.floor(Math.random() * questionContents.length)];
  }

  generateMockTags(maxCount = 1) {
    const allTags = [
      '出入登记', '产品功能', '模板讨论', '标签制作', '问题反馈',
      '行业交流', '网址码', '内容展示', '信息收集', '动态数据',
      '二维码生成'
    ];

    const tagCount = Math.floor(Math.random() * maxCount) + 1;
    const shuffled = allTags.sort(() => 0.5 - Math.random());

    return shuffled.slice(0, tagCount).map(tag => ({ name: tag }));
  }

  generateTypeSpecificData(type) {
    if (type === 'article') {
      return {
        author: '官方编辑',
        category: '技术文章',
        summary: '这是一篇关于二维码技术的详细介绍文章...',
        read_count: Math.floor(Math.random() * 5000),
        like_count: Math.floor(Math.random() * 200),
        publish_time: this.generateRandomDate(),
        url: '#'
      };
    }

    return {};
  }

  generateRandomDate() {
    const now = Date.now();
    const randomOffset = Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000); // 30天内
    return new Date(now - randomOffset).toISOString();
  }

  getMockSidebarInfo(categoryId = 0) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const sidebarData = {
          categoryName: '草料社区',
          categoryDescription: '这里汇聚了大量用户搭建二维码系统的实践经验。你可以在草料社区与各行业用户一起交流讨论、寻求帮助、吐槽产品，也可以分享自己的经验和知识。',
          hotCategories: [
            { name: '产品建议', link: '/qrcode/community/category/113' },
            { name: '表单', link: '/qrcode/community/category/77' },
            { name: '文件码', link: '/qrcode/community/category/63' },
            { name: '状态', link: '/qrcode/community/category/78' },
            { name: '签到报名', link: '/qrcode/community/category/143' },
            { name: '设备巡检', link: '/qrcode/community/category/1' },
            { name: '信息收集', link: '/qrcode/community/category/28' },
            { name: '产品介绍', link: '/qrcode/community/category/19' }
          ],
          subCategories: []
        };

        resolve({
          success: true,
          data: sidebarData
        });
      }, 200);
    });
  }

  setMockEnabled(enabled) {
    this.mockEnabled = enabled;
  }

  isMockEnabled() {
    return this.mockEnabled;
  }
}

/**
 * 社区API接口模块
 */
class CommunityApi {
  constructor() {
    this.baseUrl = window.location.hostname === 'localhost' ? 'localhost' : 'cli.im';
    this.useMockData = true;
  }

  async getCommunityList(params = {}) {
    if (this.useMockData) {
      return await mockDataService.getMockCommunityList(params);
    }

    const queryData = {
      page: params.page || 1,
      page_size: params.pageSize || 20,
      category_id: params.categoryId || 0,
      order_type: params.orderType || 'n',
      ...params
    };

    try {
      const response = await fetch(`//${this.baseUrl}/api/community/getList?` + new URLSearchParams(queryData));
      const data = await response.json();

      if (data.status === 1) {
        return {
          success: true,
          data: data.data,
          list: data.data.list || [],
          page: data.data.page || {}
        };
      } else {
        return { success: false, message: data.message || '获取数据失败' };
      }
    } catch (error) {
      console.error('获取社区列表失败:', error);
      return { success: false, message: '网络请求失败' };
    }
  }

  async getSystemCategoryList() {
    if (this.useMockData) {
      return await mockDataService.getMockCategories();
    }

    try {
      const response = await fetch(`//${this.baseUrl}/api/category/getSystemCategoryList?tree=0&group=community&modules=community`);
      const data = await response.json();

      if (data.status === 1) {
        return {
          success: true,
          data: data.data || []
        };
      } else {
        return { success: false, message: data.message || '获取分类失败' };
      }
    } catch (error) {
      console.error('获取系统分类失败:', error);
      return { success: false, message: '网络请求失败' };
    }
  }

  setUseMockData(useMock) {
    this.useMockData = useMock;
  }
}

/**
 * 数据渲染和DOM操作模块
 */
class CommunityRenderer {
  constructor() {
    this.templates = this.initTemplates();
  }

  initTemplates() {
    return {
      commentItem: `
        <div class="comment-single" style="position: relative; padding: 30px 32px;">
          <div class="comment-header" style="cursor: pointer;">
            <div class="comment-title-box" style="font-size: 16px; font-weight: 600;">
              <div class="comment-title">
                <a href="javascript:void(0)" class="title" style="color: rgba(0, 0, 0, 0.85); transition: all 0.15s ease-in-out; font-size: 19px; line-height: 26px; text-decoration: none;">{{title}}</a>
              </div>
            </div>
          </div>
          {{#if content}}<div class="comment-main-content" style="font-size: 14px; line-height: 24px; color: rgba(0, 0, 0, 0.65); padding-top: 6px; cursor: pointer; margin-bottom: 0;">{{content}}</div>{{/if}}
          <div class="comment-info-box column-flex-layout" style="font-size: 14px; flex-direction: column; align-items: flex-start; margin-top: 10px; color: rgba(0, 0, 0, 0.65);">
            <div class="more-tags-layout" style="display: flex; justify-content: space-between; width: 100%;">
              <div class="tags-from" style="display: inline-flex; flex-wrap: wrap; color: #999999; line-height: 22px; position: relative;">
                {{#if tags}}{{#each tags}}<span class="comment-type-text" style="margin-right: 8px; border-radius: 4px; line-height: 22px; font-size: 14px; display: flex; align-items: center; color: rgba(0, 0, 0, 0.45); cursor: pointer; padding: 0 6px; background-color: #f8f8f8;">{{name}}</span>{{/each}}{{/if}}
                {{#if source_name}}<div class="from-info-container" style="display: flex; align-items: center; color: rgba(0, 0, 0, 0.45); cursor: pointer; padding: 0 6px; border-radius: 4px; background-color: #f8f8f8; margin-right: 16px;">来源：{{source_name}}</div>{{/if}}
              </div>
            </div>
            <div class="comment-sub-related-info-wrap" style="display: flex; justify-content: space-between; align-items: center; margin-top: 16px; width: 100%;">
              <div class="time-box" style="display: inline-flex; flex-wrap: wrap; align-items: center; line-height: 22px; position: relative; color: rgba(0, 0, 0, 0.65); font-size: 14px;">
                <span class="member-mes" style="margin-right: 4px;">{{user_name}}</span> · {{reply_count}}个回答 · {{created_time}}更新
              </div>
              <div class="reply-action" style="cursor: pointer; color: #00a13b; display: inline-flex; align-items: center; flex-shrink: 0; font-size: 14px; line-height: 130%; letter-spacing: 0.04em; white-space: nowrap;">回复</div>
            </div>
          </div>
        </div>
      `,

      articleItem: `
        <div class="comment-single" style="position: relative; padding: 30px 32px;">
          <div class="comment-header" style="cursor: pointer;">
            <div class="comment-title-box" style="font-size: 16px; font-weight: 600;">
              <div class="comment-title">
                <a href="{{url}}" target="_blank" class="title" style="color: rgba(0, 0, 0, 0.85); transition: all 0.15s ease-in-out; font-size: 19px; line-height: 26px; text-decoration: none;">{{title}}</a>
              </div>
            </div>
          </div>
          {{#if summary}}<div class="comment-main-content" style="font-size: 14px; line-height: 24px; color: rgba(0, 0, 0, 0.65); padding-top: 6px; cursor: pointer; margin-bottom: 0;">{{summary}}</div>{{/if}}
          <div class="comment-info-box column-flex-layout" style="font-size: 14px; flex-direction: column; align-items: flex-start; margin-top: 10px; color: rgba(0, 0, 0, 0.65);">
            <div class="comment-sub-related-info-wrap" style="display: flex; justify-content: flex-start; align-items: center; margin-top: 16px; width: 100%;">
              <div class="time-box" style="display: inline-flex; flex-wrap: wrap; align-items: center; line-height: 22px; position: relative; color: rgba(0, 0, 0, 0.65); font-size: 14px;">
                <span class="member-mes article-author" style="margin-right: 4px; white-space: nowrap;">{{author}}</span> · {{read_count}}次阅读 · {{publish_time}}发布
              </div>
            </div>
          </div>
        </div>
      `,

      categoryNav: `
          {{#each categories}}
          <li class="type-li category-item"
              data-category-id="{{id}}"
              data-page-id="{{page_id}}"
              data-id="{{id}}">
            <a href="javascript:;" class="type-li-a {{#if active}}active{{/if}}">
              {{name}}
              {{#if count}}
              <span class="tag-num">{{count}}</span>
              {{/if}}
            </a>
          </li>
          {{/each}}
      `
    };
  }

  renderCommentItem(item) {
    const data = this.prepareCommentData(item);
    return this.renderTemplate('commentItem', data);
  }

  renderArticleItem(item) {
    const data = this.prepareArticleData(item);
    return this.renderTemplate('articleItem', data);
  }

  renderCommunityList(items, isLoadMore = false) {
    let html = '';

    items.forEach(item => {
      if (item.target_type === 'article') {
        html += this.renderArticleItem(item);
      } else {
        html += this.renderCommentItem(item);
      }
    });

    return html;
  }

  renderCategoryNav(categories, activeCategoryId = null) {
    const data = {
      categories: categories.map(cat => ({
        ...cat,
        active: cat.id === activeCategoryId
      }))
    };

    return this.renderTemplate('categoryNav', data);
  }

  prepareCommentData(item) {
    return {
      id: item.id || '',
      target_type: item.target_type || 'comment',
      user_avatar: item.user_avatar || '/default-avatar.png',
      user_name: item.user_name || '匿名用户',
      created_time: this.formatTime(item.created_time),
      title: this.escapeHtml(item.title || ''),
      content: this.truncateText(this.escapeHtml(item.content || ''), 100),
      reply_count: item.reply_count || 0,
      tags: this.prepareTags(item.tags),
      is_admin: item.is_admin || false,
      source_name: item.source_name || ''
    };
  }

  prepareArticleData(item) {
    return {
      id: item.id || '',
      target_type: item.target_type || 'article',
      title: this.escapeHtml(item.title || ''),
      url: item.url || '#',
      author: this.escapeHtml(item.author || '官方编辑'),
      publish_time: this.formatTime(item.publish_time || item.created_time),
      category: this.escapeHtml(item.category || ''),
      summary: this.truncateText(this.escapeHtml(item.summary || item.content || ''), 100),
      read_count: this.formatNumber(item.read_count || 0)
    };
  }

  prepareTags(tags) {
    if (!Array.isArray(tags)) return [];

    return tags.map(tag => ({
      name: this.escapeHtml(typeof tag === 'string' ? tag : tag.name || ''),
      id: typeof tag === 'object' ? tag.id : null
    }));
  }

  renderTemplate(templateName, data) {
    const template = this.templates[templateName];
    if (!template) {
      console.error(`模板 ${templateName} 不存在`);
      return '';
    }

    return this.simpleTemplateEngine(template, data);
  }

  simpleTemplateEngine(template, data) {
    // 处理循环
    let result = template.replace(/\{\{#each\s+([^}]+)\}\}([\s\S]*?)\{\{\/each\}\}/g, (match, arrayPath, content) => {
      const array = this.getNestedValue(data, arrayPath.trim());
      if (!Array.isArray(array)) {
        return '';
      }

      return array.map(item => this.simpleTemplateEngine(content, item)).join('');
    });

    // 处理条件判断
    result = result.replace(/\{\{#if\s+([^}]+)\}\}([\s\S]*?)\{\{\/if\}\}/g, (match, condition, content) => {
      const value = this.evaluateCondition(condition.trim(), data);
      return value ? content : '';
    });

    // 处理变量替换
    result = result.replace(/\{\{([^}]+)\}\}/g, (match, key) => {
      const keys = key.trim().split('.');
      let value = data;

      for (const k of keys) {
        if (value && typeof value === 'object' && k in value) {
          value = value[k];
        } else {
          return '';
        }
      }

      return value !== null && value !== undefined ? String(value) : '';
    });

    return result;
  }

  evaluateCondition(condition, data) {
    const value = this.getNestedValue(data, condition);
    return Boolean(value);
  }

  getNestedValue(obj, path) {
    const keys = path.split('.');
    let result = obj;

    for (const key of keys) {
      if (result && typeof result === 'object' && key in result) {
        result = result[key];
      } else {
        return undefined;
      }
    }

    return result;
  }

  formatTime(timestamp) {
    if (!timestamp) return '';

    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;

    const minute = 60 * 1000;
    const hour = 60 * minute;
    const day = 24 * hour;

    if (diff < minute) {
      return '刚刚';
    } else if (diff < hour) {
      return `${Math.floor(diff / minute)}分钟前`;
    } else if (diff < day) {
      return `${Math.floor(diff / hour)}小时前`;
    } else if (diff < 7 * day) {
      return `${Math.floor(diff / day)}天前`;
    } else {
      return date.toLocaleDateString('zh-CN');
    }
  }

  formatNumber(num) {
    if (num < 1000) return num.toString();
    if (num < 10000) return (num / 1000).toFixed(1) + 'k';
    return (num / 10000).toFixed(1) + 'w';
  }

  escapeHtml(text) {
    if (typeof text !== 'string') return '';

    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }

  truncateText(text, maxLength) {
    if (!text || text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
  }

  updateContent(selector, html, isAppend = false) {
    const element = document.querySelector(selector);
    if (!element) {
      console.error(`元素 ${selector} 未找到`);
      return;
    }

    if (isAppend) {
      element.insertAdjacentHTML('beforeend', html);
    } else {
      element.innerHTML = html;
    }
  }

  showLoading(selector, text = '正在加载...') {
    const html = `<div class="loading-state"><span class="loading-text">${text}</span></div>`;
    this.updateContent(selector, html);
  }

  showEmpty(selector, message = '暂无数据') {
    const html = `<div class="empty-state"><div class="empty-text">${message}</div></div>`;
    this.updateContent(selector, html);
  }

  clearContent(selector) {
    const element = document.querySelector(selector);
    if (element) {
      element.innerHTML = '';
    }
  }
}

/**
 * 工具类
 */
class Utils {
  static throttle(func, limit) {
    let lastFunc;
    let lastRan;
    return function(...args) {
      if (!lastRan) {
        func.apply(this, args);
        lastRan = Date.now();
      } else {
        clearTimeout(lastFunc);
        lastFunc = setTimeout(() => {
          if ((Date.now() - lastRan) >= limit) {
            func.apply(this, args);
            lastRan = Date.now();
          }
        }, limit - (Date.now() - lastRan));
      }
    };
  }

  static debounce(func, wait, immediate = false) {
    let timeout;
    return function executedFunction(...args) {
      const later = () => {
        timeout = null;
        if (!immediate) func.apply(this, args);
      };
      const callNow = immediate && !timeout;
      clearTimeout(timeout);
      timeout = setTimeout(later, wait);
      if (callNow) func.apply(this, args);
    };
  }
}

/**
 * 事件发射器
 */
class EventEmitter {
  constructor() {
    this.events = {};
  }

  on(event, callback) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(callback);
  }

  off(event, callback) {
    if (!this.events[event]) return;

    if (callback) {
      this.events[event] = this.events[event].filter(cb => cb !== callback);
    } else {
      delete this.events[event];
    }
  }

  emit(event, ...args) {
    if (!this.events[event]) return;

    this.events[event].forEach(callback => {
      try {
        callback.apply(this, args);
      } catch (error) {
        console.error(`事件 ${event} 处理失败:`, error);
      }
    });
  }

  once(event, callback) {
    const onceWrapper = (...args) => {
      callback.apply(this, args);
      this.off(event, onceWrapper);
    };
    this.on(event, onceWrapper);
  }
}

/**
 * 社区应用主类
 */
class CommunityApp extends EventEmitter {
  constructor(options = {}) {
    super();

    this.options = {
      container: '#vue-app',
      pageSize: 20,
      autoLoad: true,
      ...options
    };

    this.api = new CommunityApi();
    this.renderer = new CommunityRenderer();

    this.state = {
      currentPage: 1,
      currentCategory: 0,
      currentOrderType: 'n',
      loading: false,
      hasMore: true,
      items: []
    };

    this.init();
  }

  async init() {
    try {
      await this.loadCategories();

      if (this.options.autoLoad) {
        await this.loadCommunityData();
      }

      await this.loadSidebarInfo();
      this.bindEvents();
      this.emit('initialized');
    } catch (error) {
      console.error('社区应用初始化失败:', error);
      this.emit('error', error);
    }
  }

  async loadCategories() {
    try {
      const result = await this.api.getSystemCategoryList();

      if (result.success) {
        this.categories = result.data;
        this.renderCategories();
        this.emit('categoriesLoaded', result.data);
      } else {
        throw new Error(result.message);
      }
    } catch (error) {
      console.error('加载分类失败:', error);
      this.emit('error', error);
    }
  }

  async loadCommunityData(isLoadMore = false) {
    if (this.state.loading) return;

    this.state.loading = true;

    try {
      if (!isLoadMore) {
        this.renderer.showLoading('#comment-lists-box');
      }

      const params = {
        page: isLoadMore ? this.state.currentPage + 1 : 1,
        pageSize: this.options.pageSize,
        categoryId: this.state.currentCategory,
        orderType: this.state.currentOrderType
      };

      const result = await this.api.getCommunityList(params);

      if (result.success) {
        const items = result.list || result.data?.list || [];

        if (isLoadMore) {
          this.state.items = [...this.state.items, ...items];
          this.state.currentPage += 1;
        } else {
          this.state.items = items;
          this.state.currentPage = 1;
        }

        this.state.hasMore = items.length === this.options.pageSize;
        this.renderCommunityList(isLoadMore);

        this.emit('dataLoaded', {
          items: this.state.items,
          isLoadMore,
          hasMore: this.state.hasMore
        });
      } else {
        if (!isLoadMore) {
          this.renderer.showEmpty('#comment-lists-box', result.message || '加载失败');
        }
        this.emit('error', new Error(result.message));
      }
    } catch (error) {
      console.error('加载社区数据失败:', error);
      if (!isLoadMore) {
        this.renderer.showEmpty('#comment-lists-box', '网络错误，请重试');
      }
      this.emit('error', error);
    } finally {
      this.state.loading = false;
    }
  }

  renderCategories() {
    if (!this.categories || !Array.isArray(this.categories)) {
      console.error('分类数据无效:', this.categories);
      return;
    }

    const html = this.renderer.renderCategoryNav(this.categories, this.state.currentCategory);
    this.renderer.updateContent('#fir-category-ul', html);

    // 隐藏加载动画占位符
    const emptyWrap = document.querySelector('.init-empty-category-wrap');
    if (emptyWrap) {
      emptyWrap.style.display = 'none';
    }
  }

  renderCommunityList(isLoadMore = false) {
    const html = this.renderer.renderCommunityList(this.state.items, isLoadMore);
    this.renderer.updateContent('#comment-lists-box', html, isLoadMore);
  }

  bindEvents() {
    // 分类切换事件
    document.addEventListener('click', (e) => {
      const categoryItem = e.target.closest('.category-item');
      if (categoryItem) {
        this.switchCategory(categoryItem.dataset.categoryId);
      }
    });

    // 标签页切换事件
    document.addEventListener('click', (e) => {
      const tabItem = e.target.closest('.tab-li');
      if (tabItem) {
        this.switchTab(tabItem.dataset.tab);
      }
    });

    // 滚动加载更多
    window.addEventListener('scroll', Utils.throttle(() => {
      if (this.shouldLoadMore()) {
        this.loadCommunityData(true);
      }
    }, 200));
  }

  async switchCategory(categoryId) {
    if (this.state.currentCategory === categoryId) return;

    this.state.currentCategory = categoryId;
    this.state.currentPage = 1;

    // 更新UI状态
    document.querySelectorAll('.category-item').forEach(item => {
      item.classList.toggle('active', item.dataset.categoryId === categoryId);
    });

    await this.loadCommunityData();
    await this.loadSidebarInfo();
  }

  async switchTab(tabType) {
    // 更新UI状态
    document.querySelectorAll('.tab-li').forEach(item => {
      item.classList.toggle('active', item.dataset.tab === tabType);
    });

    // 显示对应内容区域
    document.querySelectorAll('.conetnt-slide-wrap').forEach(wrap => {
      wrap.style.display = wrap.id === tabType ? 'block' : 'none';
    });

    this.emit('tabChanged', tabType);
  }

  shouldLoadMore() {
    if (!this.state.hasMore || this.state.loading) return false;

    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    const scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    const clientHeight = document.documentElement.clientHeight || window.innerHeight;

    return scrollTop + clientHeight >= scrollHeight - 200;
  }

  async loadSidebarInfo() {
    try {
      const result = await mockDataService.getMockSidebarInfo(this.state.currentCategory);

      if (result.success) {
        this.sidebarInfo = result.data;
        this.renderCategoryInfo();
        this.renderHotCategories();
        this.emit('sidebarInfoLoaded', result.data);
      } else {
        throw new Error(result.message || '加载右侧边栏信息失败');
      }
    } catch (error) {
      console.error('加载右侧边栏信息失败:', error);
      this.emit('error', error);
    }
  }

  renderCategoryInfo() {
    if (!this.sidebarInfo) return;

    const categoryNameEl = document.querySelector('.category-name');
    if (categoryNameEl) {
      categoryNameEl.textContent = this.sidebarInfo.categoryName;
      categoryNameEl.title = this.sidebarInfo.categoryName;
    }

    const categoryDescEl = document.querySelector('.category-description');
    if (categoryDescEl) {
      categoryDescEl.textContent = this.sidebarInfo.categoryDescription;
    }
  }

  renderHotCategories() {
    if (!this.sidebarInfo) return;

    const hotCategoryContainer = document.getElementById('hot-category');
    if (hotCategoryContainer) {
      const hotCategories = this.sidebarInfo.hotCategories || [];

      const html = hotCategories.map(category =>
        `<a href="${category.link}">${category.name}</a>`
      ).join('');

      hotCategoryContainer.innerHTML = html;
    }
  }

  async refresh() {
    this.state.currentPage = 1;
    await this.loadCommunityData();
  }

  destroy() {
    this.off();
    this.renderer.clearContent(this.options.container);
    this.emit('destroyed');
  }
}

/**
 * 工厂函数，创建社区应用实例
 */
function createCommunityApp(options = {}) {
  return new CommunityApp(options);
}

// 创建服务实例
const mockDataService = new MockDataService();

// === 合并的JS代码结束 ===

export default {
  name: 'CommunityIndex',
  setup() {
    // 环境变量
    const ___ENV = 'online'

    // 账户变量
    const account = ref('')
    const tokenId = ref('')

    // 全局变量
    const isSave = ref(null)
    const front_url = ref('//static.clewm.net/cli')
    const autoVersion = ref('1754556853877')

    // 浏览器信息
    const __NEW_BROWSER_INFO = ref({
      ua: navigator.userAgent,
      language: navigator.language,
    })

    // 页面变量
    const currentExpTagId = ref(null)
    const page_id = ref('0')
    const activeTab = ref('mixflow')
    const cur_category_id = ref('0')
    const cur_category_group_id = ref('0')
    const updates_count = ref('164')

    // 全局变量
    const isUrl = ref(2)
    const file_size = ref(2)
    const is_community_list = ref('1')
    const seo_config_suffix = ref('二维码交流社区,二维码应用方案,草料产品更新,草料学院,二维码教程')

    // 静态域名配置
    const static_domain = ref('//static.clewm.net/cli')
    const data_info = ref('')

    // 百度统计
    const _hmt = ref([])

    // 社区应用实例
    let communityApp = null

    onMounted(() => {
      // 设置版本号属性
      document.documentElement.setAttribute('auto_version', autoVersion.value || 0)

      // 设置全局变量
      window.___ENV = ___ENV
      window.front_url = front_url.value
      window.$autoVersion = autoVersion.value
      window.__NEW_BROWSER_INFO = __NEW_BROWSER_INFO.value
      window._hmt = _hmt.value

      // 页面滚动处理
      if (window.location.hash === '#page-community-wrapper') {
        nextTick(() => {
          const communityWrapper = document.querySelector('#page-community-wrapper')
          if (communityWrapper) {
            communityWrapper.scrollIntoView()
          }
        })
      }

      // 动态加载资源脚本
      createDynamicScripts()
      loadStyleSheets()

      // 初始化seajs
      if (window.seajs) {
        window.seajs.use('common')
      }

      // 初始化社区应用
      initCommunityApp()
    })

    // 初始化社区应用
    const initCommunityApp = async () => {
      try {
        // 创建社区应用实例
        communityApp = createCommunityApp({
          container: '#vue-app',
          pageSize: 20,
          autoLoad: true
        })

        // 监听应用事件
        communityApp.on('initialized', () => {
          console.log('社区应用初始化完成')
        })

        communityApp.on('dataLoaded', (data) => {
          console.log('社区数据加载完成:', data)
        })

        communityApp.on('categoriesLoaded', (categories) => {
          console.log('分类加载完成:', categories)
        })

        communityApp.on('error', (error) => {
          console.error('社区应用错误:', error)
        })

        // 设置全局变量供其他脚本使用
        window.__communityApp = communityApp

      } catch (error) {
        console.error('初始化社区应用失败:', error)
      }
    }

    const createDynamicScripts = () => {
      // 禁用外部脚本加载，避免重定向问题
      console.log('Dynamic scripts disabled to prevent redirects')
      return
    }

    const loadStyleSheets = () => {
      const stylesheets = [
        `${static_domain.value}/css/header_search.min.css?v=${autoVersion.value}`,
        `${static_domain.value}/css/header_solution.min.css?v=${autoVersion.value}`,
        `${static_domain.value}/css/remove-ad.min.css?v=${autoVersion.value}`
      ]

      if (account.value || location.pathname.indexOf('/deqr') !== -1) {
        stylesheets.push(`${static_domain.value}/css/cli_message.min.css?v=${autoVersion.value}`)
      }

      stylesheets.forEach(href => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = href
        document.head.appendChild(link)
      })
    }

    // 组件销毁时清理
    onUnmounted(() => {
      if (communityApp) {
        communityApp.destroy()
        communityApp = null
      }

      // 清理全局变量
      if (window.__communityApp) {
        delete window.__communityApp
      }
    })

    return {
      account,
      tokenId,
      activeTab,
      page_id,
      cur_category_id,
      cur_category_group_id,
      updates_count,
      // 暴露社区应用方法
      refreshCommunityData: () => communityApp?.refresh(),
      searchCommunity: (keyword) => communityApp?.search && communityApp.search(keyword),
      getCommunityApp: () => communityApp
    }
  }
}
</script>

<style src="../../assets/css/490815b50ee0.css" scoped/>
<style src="../../assets/css/00b58f2b8f9a.css" scoped/>
<style src="../../assets/css/e88b6e80fbce.css" scoped/>
<style src="../../assets/css/f6d6073f1386.css" scoped/>
<style src="../../assets/css/5fd66d82cf52.css" scoped/>
<style src="../../assets/css/d8ce7149a6e8.css" scoped/>
<style src="../../assets/css/204cf1072e90.css" scoped/>
<style src="../../assets/css/8cf644dff1a1.css" scoped/>
<style src="../../assets/css/7c82d8d2dd2d.css" scoped/>
<style src="../../assets/css/912350b49d45.css" scoped/>
<style src="../../assets/css/11786910057f.css" scoped/>
<style src="../../assets/css/82dc0233b1fb.css" scoped/>
<style src="../../assets/css/52f4b4a7ee30.css" scoped/>

<style scoped>

/* 内嵌CSS - 来自第62-66行 */
#top-nav-community {
  color: #00a13b;
  font-weight: bold;
}

/* 内嵌CSS - 来自第192-239行 */
@media screen and (max-device-width: 450px) {
  #issue-system-modal .modal-dialog {
    width: 100%;
    height: 100%;
  }

  .modal-backdrop.in {
    opacity: 0;
  }

  #issue-system-modal .modal-header {
    /* display: none; */
  }

  .issue-system #issue-system-modal .modal-content {
    border: none;
    height: inherit;
  }

  .modal-body.issue-system-modal-body {
    max-height: calc(100vh - 62px);
    /* margin-top: 62px; */
  }

  .issue-system #issue-system-modal .modal-content .text-right {
    text-align: center;
    background: #fff;
  }

  .top-search-wrap .search-box .header-search-form-comment > .header-search-control-comment {
    width: 100%;
  }

  #feedback-modal-tips .modal-dialog,
  #wechat-follow-modal .modal.in .modal-dialog {
    width: 90% !important;
    margin: auto;
  }

  #feedback-modal-tips .modal-content,
  #wechat-follow-modal .modal-content {
    padding: 60px 10px;
  }

  #wechat-follow-modal.modal:before {
    display: initial;
  }
}
</style>


<style scoped>
.content-box{
  margin-left: -25px;
}

/* 修复右侧边栏布局问题 - 覆盖移动端CSS */
#right-side-info-block {
  display: block !important;
  width: 340px;
  flex-shrink: 0;
  background: transparent !important;
  border-radius: 2px;
}

/* 确保在所有媒体查询下都显示右侧边栏 */
@media screen and (max-width: 450px) {
  #right-side-info-block {
    display: block !important;
  }
}

.page-community-wrapper-layout {
  display: flex !important;
  justify-content: flex-start;
  align-items: flex-start;
  max-width: 1200px;
  margin: 24px auto 0;
  gap: 24px;
  background-color: #F4F5F5;
}

.page-community-wrapper {
  flex: 1;
  max-width: 836px;
  margin-right: 0;
  background: #FFFFFF;
  border-radius: 2px;
}

/* 右侧边栏样式 - 匹配草料原站 */
.side-block {
  background: #fff !important;
  border: 1px solid rgba(231,231,231,0.6) !important;
  border-radius: 2px !important;
  padding: 18px 24px !important;
  margin-bottom: 16px !important;
  box-shadow: 0 1px 2px rgba(0,0,0,0.03) !important;
}

.side-block-name {
  font-size: 16px;
  line-height: 20px;
  color: #000000;
  border-bottom: 1px solid rgba(120, 130, 140, 0.13);
  padding-bottom: 18px;
  font-weight: bold;
  margin: 0 0 16px 0;
}

.side-block-value {
  margin-top: 16px;
}

/* 应用你提供的准确样式 */
.category-name {
  font-family: 'Microsoft YaHei UI', 'Microsoft YaHei', 'PingFang SC', 'Helvetica Neue', 'Hiragino Sans GB', 'Noto Sans', Tahoma, 'Arial', 'simsun', 'sans-serif' !important;
  font-size: 16px !important;
  line-height: 26px !important;
  font-weight: 500 !important;
  color: rgba(0, 0, 0, 0.65) !important;
  border-bottom: none !important;
  padding-bottom: 0 !important;
  margin-bottom: 12px !important;
}

.category-description {
  font-family: 'Microsoft YaHei UI', 'Microsoft YaHei', 'PingFang SC', 'Helvetica Neue', 'Hiragino Sans GB', 'Noto Sans', Tahoma, 'Arial', 'simsun', 'sans-serif' !important;
  margin-top: 12px !important;
  font-weight: 400 !important;
  font-size: 14px !important;
  line-height: 24px !important;
  color: rgba(0, 0, 0, 0.7) !important;
}

/* 热门版块标题样式 - 应用和草料社区标题相同的样式 */
.side-block-name {
  font-family: 'Microsoft YaHei UI', 'Microsoft YaHei', 'PingFang SC', 'Helvetica Neue', 'Hiragino Sans GB', 'Noto Sans', Tahoma, 'Arial', 'simsun', 'sans-serif' !important;
  font-size: 16px !important;
  line-height: 26px !important;
  font-weight: 500 !important;
  color: rgba(0, 0, 0, 0.65) !important;
  border-bottom: none !important;
  padding-bottom: 0 !important;
  margin-bottom: 12px !important;
}

/* 热门版块内容样式 */
.side-block-value {
  font-family: 'Microsoft YaHei UI', 'Microsoft YaHei', 'PingFang SC', 'Helvetica Neue', 'Hiragino Sans GB', 'Noto Sans', Tahoma, 'Arial', 'simsun', 'sans-serif' !important;
  margin-top: 12px !important;
  font-weight: 400 !important;
  font-size: 14px !important;
  line-height: 24px !important;
  color: rgba(0, 0, 0, 0.7) !important;
}

/* 热门版块链接样式 - 使用原始CSS样式 */
#hot-category a {
  padding: 4px 10px !important;
  background: #FFFFFF !important;
  border: 1px solid rgba(120, 130, 140, 0.13) !important;
  border-radius: 2px !important;
  font-weight: 400 !important;
  font-size: 14px !important;
  line-height: 150% !important;
  color: rgba(0, 0, 0, 0.65) !important;
  display: inline-block !important;
  margin: 0 10px 8px 0 !important;
  text-decoration: none !important;
}

#hot-category a:active,
#hot-category a:hover {
  background: #F7F8FA !important;
  color: rgba(0, 0, 0, 0.85) !important;
  text-decoration: none !important;
}
</style>
